#!/usr/bin/env python3

import logging.config
import os
import time
import random
from RPi.GPIO import DHT_sensor # 导入 DHT_sensor 模块 （兼容 Adafruit_DHT-1.4.0 版本）


# 高级日志配置
LOGGING_CONFIG = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'
        },
        'detailed': {
            'format': '%(asctime)s - %(name)s - %(levelname)s - %(pathname)s:%(lineno)d - %(funcName)s - %(message)s'
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'level': 'INFO',
            'formatter': 'standard',
            'stream': 'ext://sys.stdout'
        },
        'file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'level': 'DEBUG',
            'formatter': 'detailed',
            'filename': 'logs/app.log',
            'maxBytes': 10485760,  # 10MB
            'backupCount': 5,
            'encoding': 'utf-8'
        },
        'error_file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'level': 'ERROR',
            'formatter': 'detailed',
            'filename': 'logs/error.log',
            'maxBytes': 10485760,
            'backupCount': 3,
            'encoding': 'utf-8'
        }
    },
    'loggers': {
        '': {  # root logger
            'handlers': ['console', 'file', 'error_file'],
            'level': 'DEBUG',
            'propagate': False
        },
        'my_module': {
            'handlers': ['console', 'file'],
            'level': 'INFO',
            'propagate': False
        }
    }
}

def setup_logging():
    """设置日志配置"""
    # 创建日志目录
    os.makedirs('logs', exist_ok=True)
    
    # 应用配置
    logging.config.dictConfig(LOGGING_CONFIG)
    
    return logging.getLogger()

logger = setup_logging()

def led_on():
    os.system("echo none > /sys/class/leds/led1/trigger")
    os.system("echo 1 > /sys/class/leds/led1/brightness")
    logger.info("led on ....")

def led_off():
    os.system("echo none > /sys/class/leds/led1/trigger")
    os.system("echo 0 > /sys/class/leds/led1/brightness")
    logger.info("led off ....")

def capture_one():
    jpg_dir='jpgs'
    os.makedirs(jpg_dir, exist_ok=True)
    cmd=f"v4l2grab -o {jpg_dir}/capture-{random.randint(0,10000)}.jpg"
    os.system(cmd)

def get_dthll():
    # 设置传感器类型: 支持 DHT11 , DHT22 和 AM2302
    sensor=DHT_sensor.DHT11

    # 设置 GPIO 的编号, ls2k300 Pi 上链接的 gpio 编号是 74
    pin = 74 #61
    result, humidity, temperature = DHT_sensor.read_retry(sensor, pin)
    if result == 0:
     #   print('Temp={0:0.1f} C  Humidity={1:0.1f}%'.format(temperature, humidity))
        logger.info('Temp={0:0.1f} C  Humidity={1:0.1f}%'.format(temperature, humidity))
    else:
    #    print('Failed to get reading. Try again!')
        logger.warning('Failed to get reading. Try again!')

    return humidity, temperature 

def app_main(tmp_max, hum_max):
    led_off()

    while True:
        humidity, temperature = get_dthll()
        if temperature > tmp_max :
            logger.warning("temp is too high")
            capture_one()

        if humidity > hum_max:
            logger.warning('humidtiy is too high')
            led_on()
            capture_one() 
        else:
            led_off()
        time.sleep(2)


# 使用示例
if __name__ == "__main__":
    logger.info("start .........")

    tmp_max = 40
    hum_max = 40
    app_main(tmp_max, hum_max)
    # logger = setup_logging()
    
